package com.authorize.common.utils;

import com.authorize.common.core.redis.RedisCache;
import com.authorize.common.utils.spring.SpringUtils;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class RedisUtils {
    private static final int timeout = 5000;

    /**
     * 加锁
     * @param key redisKey
     * @param expireTime 过期时间（秒）
     * @param requestId 请求标识
     * @return
     */
    public static Boolean lock(String key, long expireTime, String requestId) {
        long start = System.currentTimeMillis();
        for (;;) {
            boolean ret = SpringUtils.getBean(RedisCache.class).redisTemplate.opsForValue().setIfAbsent(key, requestId, expireTime, TimeUnit.SECONDS);
            if (ret) {
                return true;
            }
            long end = System.currentTimeMillis() - start;
            if (end >= timeout) {
                return false;
            }
        }
    }

    /**
     *  释放锁
     **/
    public static Long releaseLock(String key, String requestId) {
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript,Long.class);
        Long releaseStatus = (Long) SpringUtils.getBean(RedisCache.class).redisTemplate.execute(redisScript, Collections.singletonList(key), requestId);
        return releaseStatus;
    }

}
